import 'package:flutter/material.dart';
import 'package:get/get.dart';

class SlideAnimation {
  final Widget content; // 动态内容
  final Duration duration; // 动画持续时间
  final Offset beginOffset; // 动画起始位置
  final Offset endOffset; // 动画结束位置
  final bool dismissOnBackgroundTap; // 是否允许点击蒙层关闭
  final bool showOverlay; // 是否显示蒙层
  final String? position; // 位置：'top'、'bottom' 或 null（居中）
  final Offset? customPosition; // 自定义坐标（优先级高于 'top' 和 'bottom'）

  SlideAnimation({
    required this.content,
    this.duration = const Duration(milliseconds: 300),
    this.beginOffset = const Offset(1.0, 0.0), // 默认从右侧屏幕外开始
    this.endOffset = Offset.zero, // 默认到屏幕内
    this.dismissOnBackgroundTap = true, // 默认允许点击蒙层关闭
    this.showOverlay = true, // 默认显示蒙层
    this.position, // 位置：'top'、'bottom' 或 null
    this.customPosition, // 自定义坐标
  });

  OverlayEntry? _overlayEntry;
  // 使用 GlobalKey 来获取 State
  final GlobalKey<_SlideAnimationContentState> _contentKey = GlobalKey<_SlideAnimationContentState>();
  void show() {
    _overlayEntry = OverlayEntry(
      builder: (_) {
        return _SlideAnimationContent(
          key: _contentKey, // 传入 GlobalKey
          content: content,
          duration: duration,
          beginOffset: beginOffset,
          endOffset: endOffset,
          dismissOnBackgroundTap: dismissOnBackgroundTap,
          showOverlay: showOverlay,
          position: position,
          customPosition: customPosition,
          onClose: (){
            _overlayEntry?.remove();
          },
        );
      },
    );
    Overlay.of(Get.overlayContext!).insert(_overlayEntry!);
  }

  void close() {
    if (_contentKey.currentState != null) {
      _contentKey.currentState!._closeOverlay(); // 调用 State 的关闭方法
    } 
  }
}

class _SlideAnimationContent extends StatefulWidget {
  final Widget content; // 动态内容
  final Duration duration; // 动画持续时间
  final Offset beginOffset; // 动画起始位置
  final Offset endOffset; // 动画结束位置
  final bool dismissOnBackgroundTap; // 是否允许点击蒙层关闭
  final bool showOverlay; // 是否显示蒙层
  final String? position; // 位置：'top'、'bottom' 或 null（居中）
  final Offset? customPosition; // 自定义坐标
  final VoidCallback onClose; // 动画结束后关闭 OverlayEntry 的回调

  const _SlideAnimationContent({
    required Key key,
    required this.content,
    required this.duration,
    required this.beginOffset,
    required this.endOffset,
    required this.dismissOnBackgroundTap,
    required this.showOverlay,
    required this.position,
    required this.customPosition,
    required this.onClose,
  }) : super(key: key);

  @override
  State<_SlideAnimationContent> createState() => _SlideAnimationContentState();
}

class _SlideAnimationContentState extends State<_SlideAnimationContent>
    with SingleTickerProviderStateMixin {
  late final AnimationController _controller;
  late final Animation<Offset> _offsetAnimation;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      vsync: this,
      duration: widget.duration,
    );

    _offsetAnimation = Tween<Offset>(
      begin: widget.beginOffset,
      end: widget.endOffset,
    ).animate(CurvedAnimation(
      parent: _controller,
      curve: Curves.easeInOut,
    ));

    // 播放进入动画
    _controller.forward();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  /// 内部方法：播放反向动画并关闭
  void _closeOverlay() {
    _controller.reverse().then((_) => widget.onClose());
  }

  @override
  Widget build(BuildContext context) {
    Widget contentWidget;

    if (widget.customPosition != null) {
      // 自定义坐标
      contentWidget = Positioned(
        left: widget.customPosition!.dx,
        top: widget.customPosition!.dy,
        child: SlideTransition(
          position: _offsetAnimation,
          child: Material(
            color: Colors.transparent,
            child: widget.content,
          ),
        ),
      );
    } else if (widget.position == 'top') {
      // 顶部
      contentWidget = Align(
        alignment: Alignment.topCenter,
        child: Padding(
          padding: const EdgeInsets.only(top: 50.0),
          child: SlideTransition(
            position: _offsetAnimation,
            child: Material(
              color: Colors.transparent,
              child: widget.content,
            ),
          ),
        ),
      );
    } else if (widget.position == 'bottom') {
      // 底部
      contentWidget = Align(
        alignment: Alignment.bottomCenter,
        child: Padding(
          padding: const EdgeInsets.only(bottom: 50.0),
          child: SlideTransition(
            position: _offsetAnimation,
            child: Material(
              color: Colors.transparent,
              child: widget.content,
            ),
          ),
        ),
      );
    } else {
      // 居中（默认）
      contentWidget = Center(
        child: SlideTransition(
          position: _offsetAnimation,
          child: Material(
            color: Colors.transparent,
            child: widget.content,
          ),
        ),
      );
    }

    return Stack(
      children: [
        if (widget.showOverlay)
          GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: widget.dismissOnBackgroundTap ? _closeOverlay : null,
            child: Container(
              width: double.infinity,
              height: double.infinity,
              color: const Color.fromARGB(255, 25, 25, 25).withOpacity(0.7),
            ),
          ),
        contentWidget,
      ],
    );
  }
}

